package com.example.controller;


import com.alibaba.fastjson.JSON;
import com.example.entity.Student;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author yeweilin
 */
@RestController
public class Producer {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @GetMapping("/sendmsg/{msg}/{time}")
    public String send(@PathVariable("msg")String msg,@PathVariable("time")Integer time){
        CorrelationData correlationData = new CorrelationData(msg);
        rabbitTemplate.convertAndSend("A","ABC",msg,message -> {
            Integer timeLen=ThreadLocalRandom.current().nextInt(1000000)+time;
            message.getMessageProperties().setExpiration((timeLen.toString()));
         return message;
        },correlationData);
        return "OK";
    }
    @GetMapping("/out/{msg}")
    public String outTest(@PathVariable("msg") String msg){
        CorrelationData correlationData = new CorrelationData("5");
            rabbitTemplate.convertAndSend("outtest","",msg.toString(),
                    message -> {
                message.getMessageProperties().setPriority(Integer.parseInt(msg));
                return message;
                    },
                    correlationData);
        return "OK";
    }

    @GetMapping("/sendproducer")
    public String AMQP(){
        Student student = new Student(1,"lihua", LocalDateTime.now());
        Student student1 = new Student(2,"lihua", LocalDateTime.now());
        Student student2 = new Student(3,"lihua", LocalDateTime.now());
        Student student3 = new Student(4,"lihua", LocalDateTime.now());
        List<Student> students = new ArrayList<>();
        students.add(student);
        students.add(student1);
        students.add(student2);
        students.add(student3);
        String s = JSON.toJSONString(students);
        rabbitTemplate.convertAndSend("A","a",
                s,message -> {
            return message;
                },new CorrelationData("5"));
        return "OK";
    }
}
